import urlConfig from './config.js'
import tui from '../tui.js'
import {useMainStore} from '../../store/index.js'

const fetch = {
	toast: function(tips) {
		uni.showToast({
			title: tips || "出错啦~",
			icon: 'none',
			duration: 2000
		})
	},
	request: function(url, postData, method, type, hideLoading) {
		//接口请求
		if (hideLoading) {
			uni.showLoading({
				mask: true,
				title: '请稍候...'
			})
		}
	
		let token = uni.getStorageSync('TOKEN')
	
		return new Promise((resolve, reject) => {
			const mainStore = useMainStore()  //放在这里就正常了
			// console.log('请求参数', postData&&postData.pageNum&&postData.pageSize)
			uni.request({
				// url: urlConfig + url + (postData&&postData.pageNum&&postData.pageSize ? `?pageNum=${postData.pageNum}&pageSize=${postData.pageSize}` : ''),
				url: urlConfig + url,
				data: postData,
				header: {
					'content-type': type ? 'application/x-www-form-urlencoded' : 'application/json',
					'token': token
				},
				method: method, //'GET','POST'
				// responseType: imgres ? 'arraybuffer' : ' ', //转化二进制图片，主要用作登录数字验证（小程序不需要）
				dataType: 'json',
				// sslVerify: false,
				success: (res) => {
					console.log('resssssssss', res.data)
					hideLoading && uni.hideLoading()
					if (res.data.code == 200 || res.data.byteLength) {
						resolve(res)
					} else {
						switch (res.data.code) {
							case 401:
								res.data.msg ? tui.toast(res.data.msg) : ''
								break
							case 700:
								res.data.message = '登录过期，请重新登录'
								//清除 Token 用户信息并返回登录页
								uni.setStorageSync('TOKEN', "")
								uni.setStorageSync("USER_INFO", "")
								mainStore.userInfo = {}
							
								uni.$u.throttle(()=>{
									setTimeout(()=>{
										// 跳转至登录页
										uni.navigateTo({
											url:"/pages/my/login"
										})
									}, 500)
								}, 1000)
								
								break
							case 500:
								if(res.data.msg == '用户数据不存在'){
									tui.toast(res.data.msg + ',' + '请重新登录')
									setTimeout(() => {
										uni.clearStorageSync()
										uni.navigateTo({
											url:"/pages/login/login"
										})
									},1000)
								}else {
									res.data.msg ? tui.toast(res.data.msg) : ''
								}
						}
						tui.toast(res.data.message)
						reject(res)
					}
				},
				fail: (res) => {
					hideLoading && uni.hideLoading()
					console.log(res)
					if (!hideLoading) {
						this.toast("网络不给力，请稍后再试~")
					}
				}
			})
		})
	},
}

export default {
	request: fetch.request,
	toast: fetch.toast
}
